﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using System.Threading;
using MvcEngine.Core.Configuration;
using System.Globalization;
using MvcEngine.Core.Helpers;

namespace MvcEngine.Core.Localization
{
    public static class LocalizationUtil
    {
        public static IList<LanguageInfo> GetLanguages()
        {
            List<LanguageInfo> languages = ConfigurationUtil.Current.Languages;
            foreach (LanguageInfo item in languages)
            {
                item.Name = ResourceReader.Current.GetString(item.Name, item.Name);
            }

            return languages;
        }

        public static void SetThreadLanguage(HttpRequestBase request)
        {
            CultureInfo cultureInfo = null;

            if (SiteContext.Current.Site.Culture != "auto")
            {
                cultureInfo = GetCulture(SiteContext.Current.Site.Culture);
            }
            else
            {
                HttpCookie cookie = request.Cookies[Constants.UserSettings.SelectedCulture] as HttpCookie;
                if (cookie != null)
                {
                    cultureInfo = GetCulture(cookie.Value);
                }
                if (cultureInfo == null)
                {
                    string culture = null;
                    //string currentCulture = Thread.CurrentThread.CurrentCulture.ToString();
                    //if (LocalizationUtil.GetLanguages().Any(l => l.ShortName == currentCulture))
                    //{
                    //    culture = currentCulture;
                    //}
                    //else
                    //{
                    culture = SiteContext.Current.Site.Culture;
                    //}
                    cultureInfo = GetCulture(culture);
                }
            }

            if (cultureInfo != null)
            {
                Thread.CurrentThread.CurrentCulture = cultureInfo;
                Thread.CurrentThread.CurrentUICulture = cultureInfo;
            }
        }


        private static CultureInfo GetCulture(string shortName)
        {
            try
            {
                return new CultureInfo(shortName);
            }
            catch (ArgumentException ex)
            {
                LogHelper.Current.WriteError(string.Format("Language is not supported: {0}", shortName), ex);
            }
            return null;
        }
    }
}
